import os

from google.appengine.ext import db
from google.appengine.ext.webapp import template

from model import Size

from tools import manager

class SizeManager(manager.Manager):
    """
    """

    def get_size(self, size_key):
        # get asked language
        if size_key and not size_key == '':
            return Size().get(size_key)
        else:
            return ''

    def edit(self, size_name=None, size_key=None):
        """
        """
        if size_name and not size_name == '':
            query = Size().all()
            query = query.filter('name =', size_name)
            size_to_edit = query.get()
        elif size_key and not size_key == '':
            size_to_edit = Size().get(size_key)
        else:
            size_to_edit = self.get_default_size()

        # set the template for edit
        self.template_values['size_to_edit'] = size_to_edit

        # find the template
        path = os.path.join(os.path.dirname(__file__),
                            '../templates', 'size', 'edit.html')

        # display the contact
        return template.render(path, self.template_values)

    def new_size(self):
        """
        """
        # create a new size
        size = Size()
        # set a name
        size.name = db.Category(' ')
        # default width
        size.width = 1024
        # default current false
        size.default = False
        # db update
        size.put()

        # key return
        return size.key()

    def save(self, size_key, name, width, default):
        """
        """
        if default:
            # get all
            query = Size().all()

            # disable all defaults
            for size in query:
                size.default = False
                size.put()

        #
        size = Size().get(size_key)

        # set the id
        name = name.strip()
        # can't be empty
        if name == '':
            name = ' '

        # set
        size.name = db.Category(name)
        # set the title
        size.width = width
        # set default
        size.default = default
        # db update
        size.put()
        # return at the end (useful)
        return size

    def delete(self, size_key):
        """
        """
        # language to delete
        asked_size = Size().get(size_key)

        # default reset
        if asked_size.default:
            # set the current size as default
            self.size.default = True
            # save
            self.size.put()

        # delete from db
        asked_size.delete()
